package com.chenbei.erp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenbei.common.exception.LogicHandleException;
import com.chenbei.erp.domain.ProductUnit;
import com.chenbei.erp.vo.req.ProductUnitReq;
import com.chenbei.erp.mapper.ProductUnitMapper;
import com.chenbei.erp.service.IProductUnitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ProductUnitService extends ServiceImpl<ProductUnitMapper, ProductUnit> implements IProductUnitService {

    @Override
    public void add(ProductUnit productUnit) {
        LambdaQueryWrapper<ProductUnit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProductUnit::getName, productUnit.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicHandleException("单位名称已存在");
        }
        save(productUnit);
    }

    @Override
    public void update(ProductUnit productUnit) {
        LambdaQueryWrapper<ProductUnit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(ProductUnit::getId, productUnit.getId())
                .eq(ProductUnit::getName, productUnit.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicHandleException("单位名称已存在");
        }
        updateById(productUnit);
    }

    @Override
    public Page<ProductUnit> pageList(ProductUnitReq ProductUnitReq) {
        Page<ProductUnit> pageConfig = new Page<>(ProductUnitReq.getPageNum(), ProductUnitReq.getPageSize());
        LambdaQueryWrapper<ProductUnit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(ProductUnitReq.getName())) {
            lambdaQueryWrapper.like(ProductUnit::getName, ProductUnitReq.getName());
        }
        lambdaQueryWrapper.orderByDesc(ProductUnit::getId);
        return page(pageConfig, lambdaQueryWrapper);
    }

    @Override
    public void delete(Long id) {
        removeById(id);
    }

    @Override
    public List<ProductUnit> list(ProductUnitReq req) {
        LambdaQueryWrapper<ProductUnit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(req.getName())) {
            lambdaQueryWrapper.like(ProductUnit::getName, req.getName());
        }
        return list(lambdaQueryWrapper);
    }
}
